"""
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-ws2812-research
"""
from machine import Timer, RTC, reset
import ntptime
from drivers.button import Button
from config import Config
from wifihandler import WifiHandler
from ws2812 import WS2812MatrixClock

TIMEZONE = 8

clock = WS2812MatrixClock()
clock.clear()
clock.set_brightness(20)

timer_count = 0
power_on = True

rtc = RTC()
ntptime.host = 'ntp.ntsc.ac.cn'


def button_click_cb(pin):
	global power_on

	# print(f'Key {Config.KEYS.KEY_MAP[pin]} clicked')

	if pin == Config.KEYS.KEY_1:
		clock.set_brightness(clock.brightness - 20)
		show_time()
	elif pin == Config.KEYS.KEY_2:
		pass
	elif pin == Config.KEYS.KEY_3:
		pass
	elif pin == Config.KEYS.KEY_4:
		power_on = not power_on

		clock.power_on() if power_on else clock.power_off()

def sync_time(retry=3):
	if WifiHandler.is_sta_connected():
		print('sync time')
		for _ in range(retry):
			try:
				ntptime.settime()
				break
			except OSError as ose:
				if str(ose) == '[Errno 116] ETIMEDOUT':
					pass
	else:
		print('no wifi connected')

def show_time():
	datetime = rtc.datetime()
	hour = datetime[4] + TIMEZONE
	minute = datetime[5]

	clock.set_hour(hour)
	clock.set_minute(minute)
	clock.show()

def timer_cb(timer):
	global timer_count

	show_time()

	timer_count += 1
	if timer_count >= 60:
		timer_count = 0
		sync_time()


if __name__ == '__main__':
	if WifiHandler.STATION_CONNECTED == WifiHandler.set_sta_mode(Config.WIFI.SSID, Config.WIFI.PASSWORD):
		sync_time()
		show_time()

		buttons = Button(Config.KEYS.KEY_LIST, click_cb=button_click_cb)
		timer = Timer(0)

		timer.init(
			mode=Timer.PERIODIC,
			period=1000 * 60,
			callback=timer_cb
		)
	else:
		reset()
